package com.movie.admin.controller;

import com.movie.admin.entity.User;
import com.movie.admin.service.UserService;
import com.movie.admin.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.userdetails.UserDetails;

@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private com.movie.admin.security.JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        com.movie.admin.entity.User user = userService.lambdaQuery()
                .eq(com.movie.admin.entity.User::getUsername, username)
                .eq(com.movie.admin.entity.User::getPassword, password)
                .one();
        if (user != null) {
            // 生成token
            org.springframework.security.core.userdetails.UserDetails userDetails = org.springframework.security.core.userdetails.User.withUsername(user.getUsername()).password(user.getPassword()).authorities("USER").build();
            String token = jwtTokenUtil.generateToken(userDetails);
            Map<String, Object> result = new HashMap<>();
            result.put("message", "登录成功");
            result.put("userId", user.getId());
            result.put("username", user.getUsername());
            result.put("isAdmin", user.getIsAdmin());
            result.put("token", token);
            return ResponseEntity.ok(result);
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "用户名或密码错误");
            return ResponseEntity.status(403).body(result);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            if (user.getUsername() == null || user.getPassword() == null ||
                user.getUsername().trim().isEmpty() || user.getPassword().trim().isEmpty()) {
                return ResponseEntity.badRequest().body("用户名和密码不能为空");
            }
            // 检查用户名是否已存在
            boolean exists = userService.lambdaQuery().eq(User::getUsername, user.getUsername()).exists();
            if (exists) {
                return ResponseEntity.badRequest().body("用户名已存在");
            }
            userService.save(user);
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("注册失败：" + e.getMessage());
        }
    }
} 